<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2024/2/8
  Time: 18:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>新增用户信息--异步</title>
</head>
<body>
<p>用户名：<input id="username" type="text" name="username"></p>
<p>密码：<input id="password" type="password" name="password"></p>
<p>年龄：<input id="age" type="number" name="age"></p>
<p>
  <button id="btn-save">保存</button>
</p>
<script src="../../statics/js/ jquery-3.7.1.js"></script>
<script>
    <%--$(function () {--%>
    <%--    $("#btn-save").click(function () {--%>
    <%--        let user = {};--%>
    <%--        user.username = $("input[name = 'username']").val();--%>
    <%--        user.password = $("input[name = 'password']").val();--%>
    <%--        user.age = $("input[name = 'age']").val();--%>
    <%--        $.ajax({--%>
    <%--            type: 'post',--%>
    <%--            url: '<%=request.getContextPath()%>/user2/add1',--%>
    <%--            data: "user" + JSON.stringify(user),--%>
    <%--            dataType: 'json',--%>
    <%--            success: function (data) {--%>
    <%--                if (data.code == "200") {--%>
    <%--                    alert("添加成功！");--%>
    <%--                } else {--%>
    <%--                    alert("添加失败！");--%>
    <%--                    console.log(data.message);--%>
    <%--                }--%>
    <%--            },--%>
    <%--            error: function (e) {--%>
    <%--                console.log(e);--%>
    <%--            }--%>
    <%--        })--%>
    <%--    });--%>
    <%--})--%>

    document.getElementById("btn-save").onclick=function (){
        let user={};
        user.username = document.getElementById("username").value
        user.password = document.getElementById("password").value
        user.age = document.getElementById("age").value

        let xmlHttpRequest = new XMLHttpRequest();
        xmlHttpRequest.onreadystatechange=function () {
            if(xmlHttpRequest.readyState==4){
                if(xmlHttpRequest.status==200){
                    alert("ok");
                }else{
                    alert("error");
                }
            }
        }
        xmlHttpRequest.open("post","<%=request.getContextPath()%>/user2/add1")
        xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
        xmlHttpRequest.send("user=" + JSON.stringify(user));
    }
</script>
</body>
</html>
